package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.core.action.ActionInspectorCenter;
import info.batcloud.fanli.core.action.domain.UserActivationAction;
import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.entity.User;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.repository.UserRepository;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/page/user-invitation")
@PreAuthorize("hasRole('USER')")
public class PageUserInvitationController {

    @Inject
    private UserRepository userRepository;

    @Inject
    private ActionInspectorCenter actionInspectorCenter;

    @GetMapping("/data")
    @Transactional
    public Object data(@RequestParam long superUserId) {
        User superUser = userRepository.findOne(superUserId);
        User user = userRepository.findOne(SecurityHelper.loginUserId());
        if (user.getSuperUser() == null && user.getId() != superUserId) {
            user.setSuperUser(superUser);
            userRepository.save(user);
            UserActivationAction activationAction = new UserActivationAction();
            activationAction.setSuperUserId(superUserId);
            activationAction.setUserId(SecurityHelper.loginUserId());
            actionInspectorCenter.inspect(activationAction);
        }
        Map<String, Object> modelMap = new HashMap<>();
        modelMap.put("superUserAvatar", superUser.getAvatarUrl());
        modelMap.put("superUserNickname", superUser.getNickname());
        return BusinessResponse.ok(modelMap);
    }

}
